package com.example.springmvcinterceptor.config;

import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Calendar;
@Controller
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handle) throws IOException {
        //用户请求/admin开头路径时，判断用户是否登录

        String uri = request.getRequestURI();

        Object loginUser = request.getSession().getAttribute("loginUser");
        if (uri.startsWith("/admin") & null == loginUser)
            response.sendRedirect("/toLoginPage");
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handle, ModelAndView modelAndView) {
        int i=Calendar.getInstance().get(Calendar.YEAR);
       request.setAttribute("currentYear",i);
    }

}
